# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib.gis.db import models
from easy_thumbnails.fields import ThumbnailerImageField
from core.util import create_qrcode
from xpinyin import Pinyin
from django.core.files.base import ContentFile
from easy_thumbnails.files import get_thumbnailer

# Create your models here.


class ObjStatusKPI(models.Model):
    box = models.ForeignKey('asset.BoardBox', verbose_name=u'终端设备', on_delete=models.CASCADE)
    name = models.CharField(u"指标", max_length=64)
    desc = models.CharField(u"描述", max_length=64)
    number_value = models.FloatField(u'数值', default=0.0)
    status_value = models.CharField(u'状态值', max_length=24, default='UNSET')
    updated = models.DateTimeField("更新时间", auto_now=True)

    def __str__(self):
        self.name

    def __unicode__(self):
        return self.name
    class Meta:
        managed = True
        verbose_name = u'设备状态指标'
        verbose_name_plural = u'设备状态指标'



class Alert(models.Model):
    box = models.ForeignKey('asset.BoardBox', verbose_name=u'终端设备', on_delete=models.CASCADE)
    createdat = models.DateTimeField(u"预警时间", auto_now_add=True)
    name = models.CharField(u"指标", max_length=64)
    desc = models.CharField(u"描述", max_length=64)
    number_value = models.FloatField(u'数值', default=0.0)
    status_value = models.CharField(u'状态值', max_length=24, default='')
    content = models.CharField("说明", max_length=256, blank=True, null=True)
    status = models.CharField("状态", max_length=8, default="NEW")

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = verbose_name_plural = u'指标预警'



class Maintaince(models.Model):
    TYPE_FAULT = "FAULT"  # 故障
    TYPE_IPQC = "IPQC"  # 巡检
    TYEPS = ((TYPE_FAULT, u"故障"), (TYPE_IPQC, u"巡检"),)
    STATUS_NEW = 'NEW'
    STATUS_OUT = 'OUT'  # 派出
    STATUS_SIGN = 'SIGN'  # 签收
    STATUS_ARRIVE = 'ARRIVE'  # 到达
    STATUS_BACK = 'BACK'  # 退回
    STATUS_OVER = 'OVER'  # 完成
    STATUS_ONGOING = 'ONGOING'  # 处理中
    STATUS_ARCH = 'ARCH'  # 归档
    STATUS_ALL = ((STATUS_NEW, u"待处置"), (STATUS_OUT, u"派出"), (STATUS_SIGN, u"签收"), (STATUS_ARRIVE, u"到达"), (STATUS_BACK, u"退回"), (STATUS_OVER, u"完成"), (STATUS_ONGOING, u"处理中"), (STATUS_ARCH, u"归档"), )
    createdat = models.DateTimeField(u"登记时间", auto_now_add=True)
    box = models.ForeignKey('asset.BoardBox', verbose_name=u'资产装备', on_delete=models.CASCADE)
    type = models.CharField(u"类型", max_length=16, choices=TYEPS, default=TYPE_IPQC)
    reportTime = models.DateTimeField(u"发生时间",  null=True, blank=True,)
    title = models.CharField(u"标题", max_length=128, null=True, blank=True,)
    content = models.TextField(u'描述', null=True, blank=True,)
    pic1 = ThumbnailerImageField(u'截图/照片1', upload_to='box_maint/fault/', null=True, blank=True, default='', help_text=u'正视图')
    pic2 = ThumbnailerImageField(u'截图/照片2', upload_to='box_maint/fault/', null=True, blank=True, default='', help_text=u'侧视图')
    pic3 = ThumbnailerImageField(u'截图/照片3', upload_to='box_maint/fault/', null=True, blank=True, default='', help_text=u'俯视图')
    status = models.CharField(u'状态', max_length=16, choices=STATUS_ALL, default="NEW", blank=True, null=True)
    department = models.ForeignKey('org.Department', null=True,  blank=True, on_delete=models.SET_NULL, verbose_name=u'报告部门', help_text=u'系统自动设置为报告人所在部门', editable=False)
    reportor = models.ForeignKey('org.Person', verbose_name=u'报告人', on_delete=models.CASCADE)
    memo = models.CharField(u'备注说明', max_length=600, blank=True, null=True)
    dis_personnels = models.ManyToManyField(verbose_name=u'处置人', to='org.Person', through='maint.DisPersonnel', related_name='maint_dispersonnels', through_fields=('maint', 'receiver'), blank=True)

    def __str__(self):
        return self.title

    def clean(self):
        if self.reportor:
            self.department = self.reportor.ssbm

    class Meta:
        managed = True
        verbose_name = u'运维任务'
        verbose_name_plural = u'运维任务'


class FaultReportManager(models.Manager):
    def get_queryset(self):
        return super(FaultReportManager, self).get_queryset().filter(type=Maintaince.TYPE_FAULT)


class FaultReport(Maintaince):
    objects = FaultReportManager()

    class Meta:
        proxy = True
        verbose_name = u'故障报告'
        verbose_name_plural = u'故障报告'

    def save(self, *args, **kwargs):
        self.type = Maintaince.TYPE_IPQC
        super(FaultReport, self).save(*args, **kwargs)


class DailyCheckManager(models.Manager):
    def get_queryset(self):
        return super(DailyCheckManager, self).get_queryset().filter(type=Maintaince.TYPE_IPQC)


class DailyCheck(Maintaince):
    objects = DailyCheckManager()

    def __str__(self):
        return self.title

    class Meta:
        proxy = True
        verbose_name = u'日常巡检'
        verbose_name_plural = u'日常巡检'


class DisPersonnel(models.Model):
    createdat = models.DateTimeField(u'派单时间', auto_now_add=True)
    maint = models.ForeignKey(Maintaince, verbose_name=u"运维任务", related_name='dispolices', on_delete=models.CASCADE)
    sender = models.ForeignKey('org.Person', verbose_name=u"分派用户", related_name='asset_maint_send_users', blank=True, null=True, on_delete=models.SET_NULL,)
    receiver = models.ForeignKey('org.Person', verbose_name=u"处置用户", related_name='asset_maint_dis_users', on_delete=models.CASCADE)
    status = models.CharField(u'状态', max_length=10, choices=Maintaince.STATUS_ALL, default=Maintaince.STATUS_NEW, editable=False)

    def _send_police_desc(self):
        return u"%s" % self.send_police

    def _dis_police_desc(self):
        return u"%s" % self.dis_police

    def _dis_police_thumbnai(self):
        return self.dis_police.get_thumbnai100x100()

    def get_dis_police_department_name(self):
        return self.dis_police.get_department_name()

    def __str__(self):
        return '%s运维' % (self.receiver)

    def __unicode__(self):
        return self.__str__()

    class Meta:
        unique_together = ("sender", "maint")
        # auto_created = True  # ******for m2m ManyToManyField, must enabled.*****
        verbose_name_plural = verbose_name = u'运维派单'


class DoAction(models.Model):
    STATUS = ((Maintaince.STATUS_SIGN, u"签收"), (Maintaince.STATUS_ARRIVE, u"到达"), (Maintaince.STATUS_BACK, u"退回"), (Maintaince.STATUS_OVER, u"完成"), (Maintaince.STATUS_ONGOING, u"处理中"))
    createdat = models.DateTimeField(u'时间', auto_now_add=True)
    maint = models.ForeignKey(Maintaince, verbose_name=u"任务", related_name='actions', on_delete=models.CASCADE)
    # department = models.ForeignKey('org.Department', null=True,  blank=True, verbose_name='处置部门', help_text=u'系统自动设置为报告人所在部门')
    user = models.ForeignKey('org.Person', verbose_name=u"处置人", db_index=True, related_name="assets_maint_actions", on_delete=models.CASCADE)
    pic1 = models.ImageField(u'照片1', upload_to='asset_maint/doaction/', null=True, blank=True)
    pic2 = models.ImageField(u'照片2', upload_to='asset_maint/doaction/', null=True, blank=True)
    pic3 = models.ImageField(u'照片3', upload_to='asset_maint/doaction/', null=True, blank=True)
    content = models.TextField(u'描述', blank=True, null=True,)
    video = models.FileField(u'', upload_to='asset_maint/doaction/', null=True, blank=True)
    status = models.CharField(u'状态', max_length=8, choices=STATUS, default=Maintaince.STATUS_OUT)
    location = models.PointField(u'位置', srid=4326, null=True, blank=True, editable=False)
    # objects = models.GeoManager()

    def update_maintaince_status(self):
        if self.status == Maintaince.STATUS_OVER:
            # 反馈完成时, 任务也设置为完成状态
            self.maint.status = Maintaince.STATUS_OVER
        elif self.status in (Maintaince.STATUS_SIGN, Maintaince.STATUS_ARRIVE, Maintaince.STATUS_ONGOING):
            #任务在分拣状态时修改为执行状态
            self.maint.status = Maintaince.STATUS_ONGOING
        elif self.status == Maintaince.STATUS_BACK:
            self.maint.status = Maintaince.STATUS_BACK

    def clean(self):
        if self.police:
            self.department = self.police.ssbm
        self.update_maintaince_status()

    def __str__(self):
        return self.id

    class Meta:
        managed = True
        verbose_name = u'运维处置记录'
        verbose_name_plural = u'运维处置记录'
